package com.woyou.ui.component;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import com.citaq.ideliver.R;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class CheckUpdateDialog {

	Button ok_button, cancle_button; // 确定、取消
	TextView versionno, versionsize, updatetime, updatelog, tv;
	Window window;
	Dialog dialog;
	ProgressBar pb;
	ProgressDialog pd = null;
	com.woyou.utils.Dialog showDialog = new com.woyou.utils.Dialog();
	AlertDialog dlg1 = null;
	String UPDATE_SERVERAPK = "ideliver.apk";
	StringBuilder sb = new StringBuilder();
	Context context;
	long fileSize;
	int count = 0;
	boolean cancleUpdate = true;

	public void Dialog(final Context con, String versionnostr,
			String versionsizestr, String updatetimestr, String updatelogstr,
			final String updateUrlstr) {
		context = con;
		if (dialog != null && dialog.isShowing()) {
			return;
		}
		LayoutInflater factory = LayoutInflater.from(con);
		// 得到自定义对话框
		final View DialogView = factory.inflate(R.layout.checkupdatedialog,
				null);
		dialog = new Dialog(con, R.style.FullHeightDialog);
		Window dialogWindow = dialog.getWindow();
		dialogWindow.setGravity(Gravity.BOTTOM);

		versionno = (TextView) DialogView.findViewById(R.id.versionno);
		versionsize = (TextView) DialogView.findViewById(R.id.versionsize);
		updatetime = (TextView) DialogView.findViewById(R.id.updatetime);
		updatelog = (TextView) DialogView.findViewById(R.id.updatelog);

		ok_button = (Button) DialogView.findViewById(R.id.ok_button);
		cancle_button = (Button) DialogView.findViewById(R.id.cancle_button);

		pb = (ProgressBar) DialogView.findViewById(R.id.down_pb);
		tv = (TextView) DialogView.findViewById(R.id.tv);

		versionno.setText(versionnostr);
		versionsize.setText(versionsizestr);
		updatetime.setText(updatetimestr);
		updatelog.setText(updatelogstr);

		ok_button.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				pd = new ProgressDialog(con);
				pd.setTitle("正在连接");
				pd.setMessage("请稍后...");
				pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
				pd.show();
				downFile(updateUrlstr);
			}
		});
		cancle_button.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				cancleUpdate = false;
				dialog.dismiss();
			}
		});
		dialog.setContentView(DialogView);
		dialog.setCancelable(true);
		try {
			dialog.show();
		} catch (Exception e) {
			e.printStackTrace();
		}

		Window win = dialog.getWindow();
		win.getDecorView().setPadding(0, 0, 0, 0);
		WindowManager.LayoutParams lp = win.getAttributes();
		lp.width = WindowManager.LayoutParams.MATCH_PARENT;
		lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
		win.setAttributes(lp);
	}

	public void dismiss(){
		if ( dialog!=null && dialog.isShowing() ) {
			dialog.dismiss();
		}
	}
	
	/**
	 * 下载apk
	 */
	public void downFile(final String url) {
		new Thread() {
			public void run() {
				HttpClient client = new DefaultHttpClient();
				HttpGet get = new HttpGet(url);
				HttpResponse response;
				try {
					response = client.execute(get);
					HttpEntity entity = response.getEntity();
					long length = entity.getContentLength();
					fileSize = (int) entity.getContentLength();
					InputStream is = entity.getContent();
					FileOutputStream fileOutputStream = null;
					if (is != null) {
						File file = new File(
								Environment.getExternalStorageDirectory(),
								UPDATE_SERVERAPK);
						fileOutputStream = new FileOutputStream(file);
						byte[] b = new byte[1024];
						int charb = -1;
						count = 0;
						sendMsg(0);
						while ((charb = is.read(b)) != -1 && cancleUpdate) {
							fileOutputStream.write(b, 0, charb);
							count += charb;
							sendMsg(1);// 更新进度条
						}
						if (cancleUpdate) {
							sendMsg(2);// 通知下载完成
						}
					}
					fileOutputStream.flush();
					if (fileOutputStream != null) {
						fileOutputStream.close();
					}
					if (cancleUpdate) {
						down();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}.start();
	}

	Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			if (!Thread.currentThread().isInterrupted()) {
				switch (msg.what) {
				case 0:
					pd.dismiss();
					pb.setMax((int) fileSize);
				case 1:
					updatelog.setVisibility(View.GONE);
					ok_button.setVisibility(View.GONE);
					pb.setVisibility(View.VISIBLE);
					tv.setVisibility(View.VISIBLE);
					pb.setProgress(count);
					int result = count * 100 / (int) fileSize;
					tv.setText(result + "%");
					break;
				case 2:
					dialog.dismiss();
					update();
					break;

				case -1:
					String error = msg.getData().getString("error");
					Toast.makeText(context, error, 1).show();
					break;
				}
			}
			super.handleMessage(msg);
		}
	};

	private void sendMsg(int flag) {
		Message msg = new Message();
		msg.what = flag;
		handler.sendMessage(msg);
	}

	/**
	 * 下载完成，通过handler将下载对话框取消
	 */
	public void down() {
		new Thread() {
			public void run() {
				Message message = handler.obtainMessage();
				handler.sendMessage(message);
			}
		}.start();
	}

	/**
	 * 安装应用
	 */
	public void update() {
		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setDataAndType(Uri.fromFile(new File(Environment
				.getExternalStorageDirectory(), UPDATE_SERVERAPK)),
				"application/vnd.android.package-archive");
		context.startActivity(intent);
		
	}
}
